package org.truenewx.tnxjeex.unit.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.type.SimpleType;
import org.truenewx.tnxjeex.unit.model.MeasureUnit;
import org.truenewx.tnxjeex.unit.support.MeasureUnits;

public class MeasureUnitDeserializer<U extends MeasureUnit<?>> extends StdDeserializer<U> {

    public MeasureUnitDeserializer(Class<U> valueClass) {
        super(SimpleType.constructUnsafe(valueClass));
    }

    @Override
    @SuppressWarnings("unchecked")
    public U deserialize(JsonParser parser, DeserializationContext context) throws IOException, JacksonException {
        Class<U> unitClass = (Class<U>) getValueType().getRawClass();
        String key = parser.getValueAsString();
        return MeasureUnits.getInstance().fromKey(unitClass, key);
    }

}
